var tableColumns={
	CONTRACT_NO_COLUMN:{display : '合约编号', code : '', width : 100,  type:'text', value:''},
	CONTRACT_NAME_COLUMN:{display : '合约名称', code : '', width : 100,  type:'text', value:''},
	DEAL_NO_COLUMN:{display : '协议编号', code : '', width : 100,  type:'text', value:''},
	DEAL_NAME_COLUMN:{display : '协议名称', code : '', width : 100,  type:'text', value:''},
	PARTNER_NO_COLUMN:{display : '机构编号', code : 'cooperorgCode', width : 100,  type:'text', value:''},
	PARTNER_NAME_COLUMN:{display : '机构名称', code : 'cooperorgName', width : 100,  type:'text', value:''}
};



function creditSettle(obj){
		if(!$("#selectPackage").val()||!$("#abnormalSettle").val()||!$("#idSettleDate").val()){
			alert("债权包、异常类型和结算日期不能为空！");
			return;
		}
var url=contextRootPath+"/export/exportSettle?contractCode="+$("#dtocontractCode").val()+"&packageNum="
	+$("#selectPackage").val()+"&templateType="+cimsConstant.DEAL_TYPE_CREDIT_SETTLE+"&dealCode="
	+$("#dealCode").val()+"&abnormalSettle="+$("#abnormalSettle").val()+"&cooperorgCode="+$("#dtocooperorgCode").val()+"&dealType="+cimsConstant.DEAL_TYPE_CREDIT_SETTLE
	+"&settleFlag="+$("#settleFlag").val() + "&settleDate=" + $("#idSettleDate").val();
Cmm.download($("#dtocontractCode").val(), cimsConstant.DEAL_TYPE_CREDIT_SETTLE, url);
}

function monthSettle(){
	if(!$("#selectPackage").val()||!$("#idSettleDate").val()){
		alert("债权包和结算日期不能空！");
		return;
	}
	
var url=contextRootPath+"/export/exportSettle?contractCode="+$("#dtocontractCode").val()+"&packageNum="
	+$("#selectPackage").val()+"&templateType="+cimsConstant.DEAL_TYPE_MONTH_BACK
	+"&dealCode="+$("#dealCode").val()+"&cooperorgCode="+$("#dtocooperorgCode").val() +"&dealType="+cimsConstant.DEAL_TYPE_MONTH_BACK
	+"&settleFlag="+$("#settleFlag").val()  + "&settleDate=" + $("#idSettleDate").val();
Cmm.download($("#dtocontractCode").val(),cimsConstant.DEAL_TYPE_MONTH_BACK,url);
}


function creditSettleLoan(){
	if(!$("#selectPackage").val()||!$("#abnormalSettle").val()||!$("#idSettleDate").val()){
		alert("债权包、异常类型和结算日期不能为空！");
		return;
	}
var url=contextRootPath+"/export/exportSettle?contractCode="+$("#dtocontractCode").val()+"&packageNum="
+$("#selectPackage").val()+"&templateType="+cimsConstant.DEAL_TYPE_CREDIT_SETTLE+"&dealCode="
+$("#dealCode").val()+"&abnormalSettle="+$("#abnormalSettle").val()+"&cooperorgCode="+$("#dtocooperorgCode").val()+"&dealType="+cimsConstant.DEAL_TYPE_LOAN_CREDIT_SETTLE
+"&settleFlag="+$("#settleFlag").val() + "&settleDate=" + $("#idSettleDate").val();
Cmm.download($("#dtocontractCode").val(), cimsConstant.DEAL_TYPE_CREDIT_SETTLE, url);
}

function monthSettleLoan(){
	if(!$("#selectPackage").val()||!$("#idSettleDate").val()){
		alert("债权包和结算日期不能空！");
		return;
	}
	
var url=contextRootPath+"/export/exportSettle?contractCode="+$("#dtocontractCode").val()+"&packageNum="
	+$("#selectPackage").val()+"&templateType="+cimsConstant.DEAL_TYPE_MONTH_BACK
	+"&dealCode="+$("#dealCode").val()+"&cooperorgCode="+$("#dtocooperorgCode").val() +"&dealType="+cimsConstant.DEAL_TYPE_LOAN_MONTH_BACK
	+"&settleFlag="+$("#settleFlag").val()  + "&settleDate=" + $("#idSettleDate").val();
Cmm.download($("#dtocontractCode").val(),cimsConstant.DEAL_TYPE_MONTH_BACK,url);
}


(function($){
	if(!$){
		console.error("请先加载JQuery!");
		return;
	}
	window.Cmm={};
	Cmm.constants={};
	Cmm.util={};
	Cmm.util.clone=function(object){
		var _object={};
		var i;
		for(i in object){
			var value=object[i];
			if(typeof value=="string"){
				_object[i]=value.slice();
				continue;
			}
			_object[i]=value;
		}
		return _object;
	};
	
	var util=Cmm.util;
	//初始化form所有date框
	util.dateInputInit=function(formId){
		var el=$("#"+formId+" input[name*=Date]");
		if(el.length>0){
			el.each(function(){
				var datepicker=$(this),val=datepicker.val();
				datepicker.datepicker();
				if(val){
					val=new Date(val).format("yyyy-MM-dd");
					datepicker.val(val);
				}
			});
		}else{
			el=$("#"+formId);
			var datepicker=el,val=datepicker.val();
			datepicker.datepicker();
			if(val){
				val=new Date(val).format("yyyy-MM-dd");
				datepicker.val(val);
			}
		}
	};
	//为开始结束日期添加相互校验
	util.checkDdateInit=function(startDateId,endDateId){
		var startDate=$("#"+startDateId),
			endDate=$("#"+endDateId);
		startDate.datepicker("option",{
			onClose:function(val){
				endDate.datepicker("option","minDate",val);
			}
		});
		endDate.datepicker("option",{
			onClose:function(val){
				startDate.datepicker("option","maxDate",val);
			}
		});
	}
	
	/**
	 * 自定义ajax，简化平台的ajax
	 */
	Cmm.Ajax={};
	var ajax=Cmm.Ajax;
	/**
	 * 表单提交方法
	 */
	ajax.formSubmit=function(arg){
//		if(confirm("您确认要保存当前的数据吗？")){
			var params=$("#"+arg.formId).serialize(),
			url=contextRootPath+arg.url;
			if(arg.isClose==undefined)arg.isClose=true;
			jyAjax(
					url,
					params,
					function(msg){
						//新增成功后，
//						alert(msg.msg);
						var v_status = msg.status;
						if(v_status.indexOf('ok') >-1){
							arg.callback(msg);
							if(arg.isClose){
								parent.tabs.close();
								delete parent.tabs.carouselChain;
							}
						}
					});
//		}
	};
	/**
	 * 向导前后跳转操作
	 */
	ajax.carouselAction=function(formId,currentUrl,linkUrl,action,isClose){
		var id=$("#dtoid").val(),
			upperCurrentUrl=currentUrl.charAt(0).toUpperCase()+currentUrl.slice(1),
			url=contextRootPath+"/"+linkUrl+"/prepareExecute/",
			carouselChain=parent.tabs.carouselChain,
			destId=carouselChain[linkUrl];
		id=id||0;
		/*if(!CheckUtil.formCheck(formId)){
			return;
		}*/
		ajax.formSubmit({
			formId:formId,
			url:id?"/"+currentUrl+"/update"+upperCurrentUrl:"/"+currentUrl+"/insert"+upperCurrentUrl,
			callback:function(msg){
				if(action){
					if(action=="next"){
						url=destId?(url+"toUpdate?lastPage="+msg.data.id+"&id="+destId):(url+"toAdd?lastPage="+msg.data.id);
					}else if(action=="prev"){
						url=url+"toUpdate?nextPage="+msg.data.id+"&id="+destId;
					}
					carouselChain[currentUrl]=msg.data.id;
					if(msg.data.contractCode){
						carouselChain.contractCode=msg.data.contractCode;
					}
					//window.location=url;
				}
			},
			isClose:isClose
		});
	};
	/**
	 * 加载定义好的table的column信息
	 */
	Cmm.columns=tableColumns;
	/**
	 * Cmm.baseObjects空间下放置基础对象的构造函数
	 * */
	Cmm.baseObjects={};
	var baseObjects=Cmm.baseObjects;
	/**
	 *查询项的构造函数 
	 * 
	 */
	baseObjects.BaseFormItem=function(option){
		var _this=this;
		if(typeof option=="object"){
			/*添加默认查询项*/
			if(option.isDefault){
				this.columns=baseFormItem.prototype.defaultColumns.slice();
			}else{
				this.columns=[];
			}
			var optionColumns=option.columns,columns=this.columns;
			if(optionColumns&& optionColumns instanceof Array){
				columns=columns.concat(optionColumns);
			}
			this.buttons=[
				{"text":"查询","fun":function(){_this.searchIframe.iframeObj["table"].query();},icon:"ui-icon-search"},
				{"text":"重置","fun":function(){_this.getForm().reset();},icon:"ui-icon-extlink"}
			];
		}else{
			console.error("构造器参数不能为空");			
		}
	};
	var baseFormItem=baseObjects.BaseFormItem;
	//设置默认查询项
	baseFormItem.prototype.defaultColumns=[
		{display : '合约编号', code : '', width : 100,  type:'text', value:''},
		{display : '合约名称', code : '', width : 100,  type:'text', value:''},
	];
	//获取form的方法
	baseFormItem.prototype.getForm=function(){
		var _this=this,searchIframe=_this.searchIframe;
		if(!_this.form){
			_this.form=$("#"+searchIframe.formName);
		}
		return _this.form.find('form')[0];
	};
	//设置searchIframe
	baseFormItem.prototype.setSearchIframe=function(searchIframe){
		this.searchIframe=searchIframe;
	};
	
	/**
	 * table的构造函数(选用，用于简化构造过程)
	 */
	baseObjects.BaseTableItem=function(option){
		if(option){
			this.primaryKey=option.primaryKey;
			this.url=option.url;
			this.toolbar=[];
		}else{
			console.error("必须要有构造参数");
		}
	};
	var baseTableItem=baseObjects.BaseTableItem;
	baseTableItem.prototype.pageSize=10;
	baseTableItem.prototype.selectType='checkbox';
	baseTableItem.prototype.isCheck=true;
	baseTableItem.prototype.rownumbers=true;
	baseTableItem.prototype.pages=[ 10, 20, 30 ];
	baseTableItem.prototype.trHeight=30;
	baseTableItem.prototype.form='form';
	baseTableItem.prototype.toolbar='form';
	//{text:新页面title,url:请求地址,idField:id字段名称},action操作
	baseTableItem.prototype.buildButtonAction=function(param,action){
		var _this=this;
		return function(table){
			var cloneParam=util.clone(param);
			var v_ids = table.getSelectedIds().join(",");
			if(action=="delete"){
				/*var table=_this.searchIframe.iframeObj["table"]*/
				//如果没有选中 数据则
				if(v_ids == ""){
					alert("请选择待删除的数据！");
					return;
				}
				if(confirm("您确认要删除选择的数据吗？")){
			        $.ajax({
			            type:"POST",
			            dataType : "json",
			            url:cloneParam.url+="?ids="+v_ids,
			            success:function(msg){
			            	alert(msg.msg);
			            	var v_status = msg.status;
			            	//删除成功后
			            	if(v_status.indexOf('ok') >-1){
			            		table.removeSelectedRow();
			            	}
			            }
			        });
			    }
				return;
			}else if(action!="add"){
				
				if(v_ids == ""&&action=="view"){
					alert("请选择待查看的数据！");
					return;
				}
				
				//如果没有选中 数据则
				if(v_ids == ""){
					alert("请选择待修改的数据！");
					return;
				}
				//如果选择多个 择提示
				if(v_ids.indexOf(",") > -1){
					alert("请选择一条数据！");
					return;
				}
				cloneParam.url=(cloneParam.url+"?id="+table.getSelectedIds().join(","));
			}
			parent.showObj(cloneParam);
		};
	};
	baseTableItem.prototype.setSearchIframe=function(searchIframe){
		this.searchIframe=searchIframe;
	};
	
	Cmm.CarouselUtil={};
	var carouselUtil=Cmm.CarouselUtil;
	carouselUtil.pageInit=function(formId){
		var carouselChain=parent.tabs.carouselChain,
			contractCode=carouselChain.contractCode,
			$contractCode=$("#dtocontractCode");
		if(!$contractCode.val()){
			$contractCode.val(contractCode);
		}
		if(arguments[1]!==false)
			util.dateInputInit(formId);
	};
	
	/**
	 * 生成下拉框
	 * setting={displayField:显示字段,valueField:实际字段,
	 * 			url:请求地址,onChange:change事件处理函数,
	 * 			condition:Object查询条件
	 * 			}
	 */
	$.fn.combo=function(setting){
		var combo=$(this),
			timestamp=new Date().getMilliseconds(),
			itemid=combo.attr("itemid"),
			displayField=setting.displayField,
			valueField=setting.valueField,
			dataMap={},
			/*此方法用于加载数据，并构建Dom，该方法持有setting引用，便于应对setting的变更*/
			load=function(){
				$.ajax({
					url: contextRootPath+setting.url,
					type: 'post',
					dataType: 'json',
					data:setting.condition?setting.condition:"",
					error: function(result) {
						alert("请查看返回数据是否正确：" + result.msg);
					},
					success: function(result) {
						var data=result.data,
							originVal=combo.val();
						combo.hide();
						var selector=combo.next("select[itemid='"+itemid+"']");
						var selectEl=[],optionArray=["<option value=''>--请选择--</option>"];
						$.each(data,function(index,e){
							dataMap[index]=e;
							optionArray.push("<option value='"+e[valueField]+"'");
							optionArray.push(" itemid="+index);
							if(originVal===e[valueField]){
								optionArray.push(" selected");
							}
							optionArray.push(">");
							optionArray.push(e[displayField]);
							optionArray.push("</option>");
						});
						if(selector.length==0){
							selectEl.push("<select itemid="+itemid+">");
							selectEl=selectEl.concat(optionArray);
							selectEl.push("</select>");
							combo.after(selectEl.join(""));
							selector=combo.next("select[itemid='"+itemid+"']");
							combo.attr("notNull")&&selector.attr("notNull","false");
							selector.addClass("fieldSelect");
							selector.css("min-width","133px");
							selector.on("change",function(event){
								combo.val(selector.val());
								var option=selector.find("option:selected");
								var opItemId=option.attr("itemid");
								var onChangeFun=setting.onChange;
								if(onChangeFun&&typeof onChangeFun=="function"){
									onChangeFun(this,dataMap[opItemId]);
								}
							});
						}else{
							selector.empty();
							selector.append(optionArray.join(""));
						}
						selector.trigger('change');
					}
				});
			};
		if(!itemid){
			itemid="combo_"+timestamp;
			combo.attr('itemid',itemid);
			load();
			setting.load=load;//通过增强setting参数的方式将该方法公开给调用者
		}
		return setting;
	};
	/**
	 * 级联两个下拉框
	 * main和slave为同样结构的对象,其余同combo的setting
	 * {id:目标input的id,
	 *  controlMap:{}控制字段map，主下拉框的字段值映射为从下拉框的限制条件值
	 * }
	 */
	Cmm.comboCascade=function(master,slave){
		slave.condition=slave.condition||{};
		var $slave=$("#"+slave.id),
			$master=$("#"+master.id),
			masterOnChange=master.onChange,
			controlMap=master.controlMap,
			key,
			masterValue=$master.val()||"###";
		for(key in controlMap){
			slave.condition[controlMap[key]]=masterValue;
		}
		slave=$slave.combo(slave);
		/*增加一个hook函数，hook函数控制slave下拉框*/
		master.onChange=function(combo,data){
			var cond=slave.condition,
				key;
			for(key in controlMap){
				data?cond[controlMap[key]]=data[key]:cond[controlMap[key]]="###";
				slave.load();
			}
//			$slave.val(null);
			if(masterOnChange)masterOnChange(combo,data);
		};
		$master.combo(master);
		return {master:master,slave:slave};
	};
	
	Cmm.constants.InteractRestoreUrl=contextRootPath+"/interactRestore";
	Cmm.restoreInteract=function(businessCode){
		businessCode&&confirm("发生异常，是否要重新操作？")&&jyAjax(
			Cmm.constants.InteractRestoreUrl,
			{"businessCode":businessCode},
			function(){
				alert("执行成功");
			},
			function(){
				Cmm.restoreInteract(businessCode);
			}
		  );
	};
	
	Cmm.download=function(contractCode, templateType, url){
		$.ajax({
	         type:"get",
	         dataType: 'json',
	         url:contextRootPath+"/tCMmExcelTemplate/queryListTCMmExcelTemplate?contractCode="+contractCode + "&templateType=" + templateType,
	         success:function(msg){
	        	var msgData = msg.data;
	         	var excelTemplate;
	         	if(null==msgData){
	         		excelTemplate=null;
	         	}else{
	         		excelTemplate = msgData.length;
	         	}
	         	
	        	if(null==excelTemplate || excelTemplate==0 || excelTemplate > 1){
	        		alert("未设置导出模板！");
	        		return;
	        	}else{
	        		var iframe=$("<iframe>",{
	        			 id:"downloader",
	        			 src:url
	        		 });
	        		 iframe.css("display","none");
	        		 iframe.appendTo("body");
	        	}
	         }
	     });
	};
})(jQuery);


/**
 * 级联工具方法
 */
(function($){
	window.ComboCascadeUtil={};
	var comboCascadeUtil=window.ComboCascadeUtil;
	/*合作机构-合约级联*/
	comboCascadeUtil.cascadeCooperOrgContract=function(masterId,slaveId){
		var cooperOrgSetting={
			url:'/cimsCascade/queryListCimsCascadeCooperorg',
			displayField:'cooperorgName',
			valueField:'cooperorgCode',
			id:masterId,
			controlMap:{"cooperorgCode":"cooperorgCode"}
		};
		var contractSetting={
			url:'/cimsCascade/queryListCimsCascadeContract',
			displayField:'contractName',
			valueField:'contractCode',
			id:slaveId
		};
		Cmm.comboCascade(cooperOrgSetting,contractSetting);
	};
	/*合作机构-协议级联*/
	comboCascadeUtil.cascadeCooperOrgAgreement=function(masterId,slaveId){
		var cooperOrgSetting={
				url:'/cimsCascade/queryListCimsCascadeCooperorg',
				displayField:'cooperorgName',
				valueField:'cooperorgCode',
				id:masterId,
				controlMap:{"cooperorgCode":"cooperorgCode"}
		};
		var agreementSetting={
				url:'/tCMmAgreement/queryListTCMmAgreement',
				displayField:'agreementName',
				valueField:'agreementCode',
				id:slaveId
		};
		Cmm.comboCascade(cooperOrgSetting,agreementSetting);
	};
	
})(jQuery);

(function(){
	Cmm.JY={cooperorgCode:"0",cooperorgName:"捷越"};
	Cmm.JJ={cooperorgCode:"1",cooperorgName:"居间人"};
})();

/**
 * 修改平台不足的js，平台升级以后去除
 */
(function($){
	/*修正日期正则表达式验证*/
	regExps.date=/^([1-2]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))$/;
	/*校验初始化不显示红框*/
	var oldFunc=checkedInitForm;
	checkedInitForm=function(formObj){
		oldFunc(formObj);
		$(".checkError").removeClass("checkError");
	};
	/*修正根据菜单名称取tab的缺陷*/
	$(function(){
		var tabs=parent.tabs;
		if(tabs){
			if(!tabs.urlMap){
				tabs.urlMap={};
				tabs.getTabsByDbId=function(id){
					var menusCache=parent.top.MenusCache,
					url=menusCache[id],
					tabId=this.urlMap[url];
					var tabIframe=parent.top.document.getElementById(tabId);
					return tabIframe?tabIframe.contentWindow:null;
				};
			}
			var newTab=tabs.getActiveObj();
			tabs.urlMap[newTab.url.split(contextRootPath)[1]]=newTab.id+"_Iframe";
		}
	});
})(jQuery);

//公平用查询债权包显示标签
function completePackage(selectOptions,selectID,updatePackageValue,type,table,monthSettle){
	$("#" + selectID).hide();	
	if(type=='update'){
		$("#selectPackage").val(updatePackageValue);
		$("#selectPackage").attr("disabled","disabled");
	}else{
		if(selectOptions.length>0){
			
			$( "#selectPackage").autocomplete({
			       source:selectOptions,
			       minLength: 0, 
			       delay: 300,
			       change:function(event, ui){
			    	   
			    	   var select=$("#selectPackage"),
		   		    	selectType=$("#abnormalSettle"),
		   		    	selectSettleDate=$("#idSettleDate"),
		   		    	typeArray=[],
		   		    	typeStr;
			   		    selectType.children("option").each(function(i,n){
			   		    	n.value&&typeArray.push(n.value);
			   		    });
			   		    typeStr=typeArray.join(",");
			    	   
			    	   var packageName=select.val(),
	  					types=selectType.val();
	  					settleDate=selectSettleDate.val();
	   		    		packageName = packageName?packageName:"000";
	   		    		types = types?types:"000";
	   		    		settleDate = settleDate?settleDate:"000";
	   		    	
	   		    	if(monthSettle=="monthSettle"){
	   		    		if(packageName!="000"&&settleDate!="000"){
		   	   			  	selectChange(select,selectSettleDate,table);
		   	   			  }
	   		    	}else{
	   		    		if(packageName!="000"&&types!="000"&&settleDate!="000"){
		   		    		selectChange(select,selectType,selectSettleDate,typeStr,table);
		   		    	}
	   		    	}

			       }
			    }).focus(function () {
			                $(this).autocomplete("search");
			    });
		}
	}
	
	
}

